package com.ruoyi.merchant.utils;

import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/*
* 加油站详细的内容
* */
@Component
public class SearchUtil {

    private static final String BASE_URL = "https://api.map.baidu.com/place/v2/detail?";
    private static final String AK = "CevbVOiRcKINzvmzRjHrumvMmR5IrHxt";

    public String requestGetAK(Map<String, String> params) throws Exception {
        if (params == null || params.isEmpty()) {
            throw new IllegalArgumentException("Params cannot be null or empty");
        }

        // Add default AK to params
        params.put("ak", AK);

        // Construct the query string
        StringBuilder queryString = new StringBuilder(BASE_URL);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            queryString.append(entry.getKey())
                    .append("=")
                    .append(UriUtils.encode(entry.getValue(), "UTF-8"))
                    .append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1); // Remove the trailing '&'
        }

        // Make the request
        URL url = new URL(queryString.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // Read the response
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        }
    }
}
